package org.lc.solon.cmd.impl.completer;

import org.jline.reader.Candidate;
import org.jline.reader.Completer;
import org.jline.reader.LineReader;
import org.jline.reader.ParsedLine;
import org.lc.solon.cmd.ParamsParser;
import org.lc.solon.cmd.impl.DefaultParamsParser;
import org.lc.solon.cmd.impl.SolonCommand;

import java.util.List;

public class SolonCommandCompleter implements Completer {
    final SolonCommand command;

    public SolonCommandCompleter(SolonCommand command) {
        this.command = command;
    }

    @Override
    public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
        if (line.wordIndex() == 0) {
            return;
        }
        SolonCommand.SolonMethodCommand subCmd = command.getSubCmdMap().get("");
        if (subCmd != null) {
            tryComplete(command, subCmd, reader, line, candidates);
        }
        if (line.wordIndex() == 1) {
            command.getSubCmdMap().forEach((name, cmd) -> {
                if (name.startsWith(line.word()) && !"".equals(name)) {
                    candidates.add(new Candidate(name, name, null, cmd.getDescription(), null, null, true));
                }
            });
            return;
        }
        SolonCommand.SolonMethodCommand cmd = command.getSubCmdMap().get(line.words().get(1));
        if (cmd != null) {
            tryComplete(command, cmd, reader, line, candidates);
        }
    }

    protected void tryComplete(SolonCommand cmd, SolonCommand.SolonMethodCommand subCmd, LineReader reader,
                               ParsedLine line, List<Candidate> candidates) {
        ParamsParser parser = subCmd.getConfig().getParser();
        if (parser instanceof DefaultParamsParser) {
            ((DefaultParamsParser) parser).complete(cmd, subCmd, reader, line, candidates);
        }
    }
}
